package top.january.codelabf2;

import ohos.aafwk.ability.AbilityPackage;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.utils.zson.ZSONObject;

public class MyApplication extends AbilityPackage {
    public ZSONObject global = null;
    String fileName = "test_pref"; // fileName表示文件名，其取值不能为空，也不能包含路径，默认存储目录可以通过context.getPreferencesDir()获取。
    @Override
    public void onInitialize() {
        super.onInitialize();

    }

    @Override
    public void onEnd() {
        super.onEnd();

    }

    public void loadData() {
        DatabaseHelper databaseHelper = new DatabaseHelper(this); // context入参类型为ohos.app.Context。
        Preferences preferences = databaseHelper.getPreferences(fileName);
        String dataStr = preferences.getString("data", "{}");
        global = ZSONObject.stringToZSON(dataStr);
    }

    public void saveData() {
        String dataStr = global.toString();
        DatabaseHelper databaseHelper = new DatabaseHelper(this); // context入参类型为ohos.app.Context。
        Preferences preferences = databaseHelper.getPreferences(fileName);
        preferences.putString("data", dataStr);
        preferences.flushSync();
    }
}

